package model

import (
	"errors"
	"github.com/jinzhu/gorm"
)

// ClueInfo represents a Clue info
type ClueInfo struct {
	gorm.Model
	UserID          int64  `json:"user_id"`
	Type            int64  `json:"type"`
	CameraID        int64  `json:"camera_id"`
	JobID           int64  `json:"job_id"`
	FileKey         string `json:"file_key"`
	BeginFrameIndex int64  `json:"begin_frame_index"`
	EndFrameIndex   int64  `json:"end_frame_index"`
}

// AddNewClue add a new Clue
func AddNewClue(clueInfo *ClueInfo) (interface{}, error) {
	clue := db.Save(clueInfo)
	return clue.Value, nil
}

// GetClue get a single Clue
func GetClue(ClueID string) (*ClueInfo, error) {
	var Clue ClueInfo
	// SELECT * FROM Clue WHERE id = ClueID;
	db.First(&Clue, ClueID)
	if Clue.ID == 0 {
		err := errors.New("no Clue found")
		return &ClueInfo{}, err
	}

	return &Clue, nil
}

// GetClueByUserID get clue by user id
func GetClueByUserID(userID string) ([]ClueInfo, error) {
	var Clue []ClueInfo
	if userID != "" {
		db.Where("user_id = ?", userID).Find(&Clue)
	}
	if len(Clue) == 0 {
		err := errors.New("no Clue found")
		return nil, err
	}

	return Clue, nil
}

// ExistClueByID check the id is exist or not
func ExistClueByID(ID int) bool {
	var myClue ClueInfo
	db.Select("id").Where("id = ?", ID).First(&myClue)
	if myClue.ID > 0 {
		return true
	}
	return false
}

// UpdateClue edit user info
func UpdateClue(id int, data interface{}) bool {
	db.Model(&ClueInfo{}).Where("id = ?", id).Updates(data)

	return true
}

// DeleteClue delete the user info from db
func DeleteClue(id int) bool {
	db.Where("id = ?", id).Delete(&ClueInfo{})

	return true
}

// GetAllClues get the all Clues info from db
func GetAllClues() (result []ClueInfo, err error) {
	var myClue []ClueInfo
	db.Find(&myClue)

	if len(myClue) == 0 {
		err = errors.New("no Clue found")
		return nil, err
	}
	return myClue, nil
}
